
// import  jsmediatags  from 'jsmediatags'
import { useState } from 'react';
import { parseBuffer, parseFile } from 'music-metadata';
import {toUint8Array, uint8ArrayToBase64} from 'uint8array-extras';
import { getSongFileUsingGet } from '@/services/music-recommend/songController';

export const MP3_DEFAULT_IMG = 'https://fakeimg.pl/300x300/?text=%F0%9F%8E%B6&font=noto';

// export async function  loadCover(mp3Url:string) {
//   let cover = MP3_DEFAULT_IMG;
//   jsmediatags.read(mp3Url, {
//     onSuccess: (tag) => {
//       if (tag.tags.picture && tag.tags.picture[0]) {
//         const picture = tag.tags.picture[0];
//         const coverImage = `data:${picture.format};base64,${Buffer.from(picture.data).toString('base64')}`;
//         console.log("success: ");
//         console.log(coverImage);
//         cover = coverImage;
//       }
      
//     },
//     onError: (error) => {
//       console.error('Error fetching mp3 tags:', error);
//     },
//   });
//   console.log("success: outer");
//   return cover;
// };


export async function getCover(url:string) {
  try {
    const respond = await fetch("/api/song/file/"+url);
    const buffer = await respond.arrayBuffer()
    // const metadata = await parseFile(url);
    const metadata = await parseBuffer(toUint8Array(buffer), { mimeType: 'audio/mpeg' });
    console.log("Metadata received:", metadata);
    const pic = metadata.common.picture;
    console.log("Metadata pic:", pic);
    if(pic && pic.length >0) {
      const buf = pic[0].data;
      const img = uint8ArrayToBase64(buf);
      const src = `data:${pic[0].format};base64,${img}`;
      return src;
    }
    return MP3_DEFAULT_IMG;
  } catch (error) {
    console.log("parserFile error: ",error);
    return MP3_DEFAULT_IMG;
  }
  
}